package com.molyfun.parents.zhibo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;

import com.molyfun.parents.impl.NetWorkChangeCallback;
import com.molyfun.parents.utils.NetWorkUtil;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:22/03/2018.
 */

public class NetChangeReceiver extends BroadcastReceiver {

    private static List<NetWorkChangeCallback> mCallbacks = new LinkedList<>();

    public static void addNetCallback(NetWorkChangeCallback netWorkChangeCallback){
        mCallbacks.add(netWorkChangeCallback);
    }

    public static void removeNetCallback(NetWorkChangeCallback netWorkChangeCallback){
        if(mCallbacks.contains(netWorkChangeCallback)){
            mCallbacks.remove(netWorkChangeCallback);
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        if(intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)){
            //Intent中ConnectivityManager.EXTRA_NO_CONNECTIVITY这个关键字表示着当前是否连接上了网络
            //true 代表网络断开   false 代表网络没有断开
//            if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)){
//
////                aActivity.stopFlag = true;
//            }else{
////                aActivity.stopFlag = false;
//            }

            boolean isNetWorkAvalilable = NetWorkUtil.isNetworkAvailable(context);
            boolean isInWifi = NetWorkUtil.isInWifiNetWork(context);
            if(mCallbacks.size() > 0){
                for(NetWorkChangeCallback netWorkChangeCallback : mCallbacks){
                    if(netWorkChangeCallback != null){
                        netWorkChangeCallback.onNetWorkAvailableChange(isNetWorkAvalilable);
                        netWorkChangeCallback.onNetWorkMethodChange(isInWifi);
                    }
                }
            }

        }
    }

}
